package pl.edu.mimuw.irs.rcp.controller.handler;

import java.util.Map;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import pl.edu.mimuw.irs.core.model.design.processing.Resource;
import pl.edu.mimuw.irs.core.model.design.processing.Role;
import pl.edu.mimuw.irs.rcp.controller.editor.ResourceEditor;
import pl.edu.mimuw.irs.rcp.controller.editor.input.ResourceEditorInput;
import pl.edu.mimuw.irs.rcp.util.Logger;
import pl.edu.mimuw.irs.rcp.util.MessageCode;
import pl.edu.mimuw.irs.rcp.view.ResourcesView;

public class EditResourceHandler extends AbstractHandler {

	// *** Attributes

	// *** Methods

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		ResourcesView view = (ResourcesView) page.findView(ResourcesView.ID);
		Map<String, Role> rolesMap = view.getRolesMap();
		// Get the selection
		ISelection selection = view.getSite().getSelectionProvider()
				.getSelection();
		
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object obj = structuredSelection.getFirstElement();
			// If we had a selection let's open the editor
			if (obj != null && (obj instanceof Resource)) {
				Resource resource = (Resource) obj;
				ResourceEditorInput input = new ResourceEditorInput(resource, rolesMap);
				try {
					page.openEditor(input, ResourceEditor.ID);
				} catch (PartInitException e) {
					Logger.handle(MessageCode.EDITOR_OPEN_PROBLEM, e, ResourceEditor.ID);
				}
			}
		}

		return null;
	}
}
